<template>
  <div class="container">
    <!-- <div class="sidebar">  
      <el-input placeholder="请输入关键字搜索" v-model="searchKey" />  
      <el-tree :data="treeData" :props="defaultProps" class="letree"></el-tree>  
    </div>   -->
    <div class="main">
      <div class="header">
        <el-button type="primary" @click="add">新建</el-button>
        <el-button type="success" @click="importData">导入</el-button>
        <el-button type="warning" @click="edit">编辑</el-button>
        <el-select v-model="selectedFilter" placeholder="请选择状态" style="width: 200px;">
          <el-option label="启用" value="enabled"></el-option>
          <el-option label="禁用" value="disabled"></el-option>
        </el-select>
        <el-input placeholder="请输入关键字搜索" v-model="searchTable" style="width: 200px;" />
        <el-button type="info" @click="query">查询</el-button>
        <el-button type="info" @click="reste">重置</el-button>
      </div>
      <el-table :data="tableData" border class="eltable">
        <el-table-column prop="section_id" label="序号" width="80"></el-table-column>
        <el-table-column prop="section_name" label="部门名称"></el-table-column>
        <!-- <el-table-column prop="manager_section_name" label="上级部门" width="160"></el-table-column> -->
        <el-table-column prop="section_charge" label="负责人"></el-table-column>
        <el-table-column prop="section_phone" label="电话"></el-table-column>
        <el-table-column prop="section_email" label="邮箱"></el-table-column>
        <el-table-column prop="section_create_by" label="创建人"></el-table-column>
        <el-table-column prop="section_create_time" label="创建时间"></el-table-column>
        <el-table-column prop="section_status" label="启用" width="100">
          <template #default="{ row }">
            <el-switch v-model="row.section_status" active-text="是" inactive-text="否"
              @change="handleSwitchChange(row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button type="text" @click="editRow(row)">编辑</el-button>
            <el-button type="text" @click="deleteRow(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
        :total="totalItems" layout="total, prev, pager, next, jumper">
      </el-pagination>
    </div>
  </div>
  <el-dialog v-model="dialogVisible" title="添加" width="660" :before-close="handleClose">
    <span>
      <el-form :model="form" :inline="true" class="demo-form-inline">
        <el-form-item label="部门名称" :label-width="formLabelWidth">
          <el-input v-model="form.section_name" autocomplete="off" clearable></el-input>
        </el-form-item>
        <!-- <el-form-item label="上级部门" :label-width="formLabelWidth">
          <el-input v-model="form.manager_section_name" autocomplete="off" clearable></el-input>
        </el-form-item> -->
        <el-form-item label="负责人" :label-width="formLabelWidth">
          <el-input v-model="form.section_charge" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth">
          <el-input v-model="form.section_phone" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="form.section_email" autocomplete="off" clearable></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addqr">确 定</el-button>
    </span>
  </el-dialog>
  <el-dialog v-model="dialogVisible1" title="修改" width="660" :before-close="handleClose">
    <span>
      <el-form :model="form" :inline="true" class="demo-form-inline">
        <el-form-item label="部门名称" :label-width="formLabelWidth">
          <el-input v-model="form.section_name" autocomplete="off" clearable></el-input>
        </el-form-item>
        <!-- <el-form-item label="上级部门" :label-width="formLabelWidth">
          <el-input v-model="form.manager_section_name" autocomplete="off" clearable></el-input>
        </el-form-item> -->
        <el-form-item label="负责人" :label-width="formLabelWidth">
          <el-input v-model="form.section_charge" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth">
          <el-input v-model="form.section_phone" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="form.section_email" autocomplete="off" clearable></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="dialogVisible1 = false">取 消</el-button>
      <el-button type="primary" @click="upqr">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import axios from 'axios';
import { ref } from 'vue';

export default {
  setup() {
    const userId = localStorage.getItem('userId');
    const searchKey = ref('');
    const treeData = ref([]);
    const defaultProps = {
      children: 'children',
      label: 'label',
    };
    const dialogVisible = ref(false);
    const dialogVisible1 = ref(false);
    const tableData = ref([]);

    const selectedFilter = ref('');
    const searchTable = ref('');
    const currentPage = ref(1);
    const pageSize = ref(2);
    const totalItems = ref(0);
    const form = ref({
      section_name: '',
      section_charge: '',
      section_phone: '',
      section_email: '',
    });
    const form1 = ref({
      section_id: '',
      section_name: '',
      section_charge: '',
      section_phone: '',
      section_email: '',
    });
    console.log(userId);
    console.log(currentPage);
    console.log(pageSize);
    function sx() {
      axios.get(`http://localhost:5084/api/Section/GetAll?PageNumber=${currentPage.value}&PageSize=${pageSize.value}`)
        .then(response => {
          console.log(response.data);

          // 更新总条目数
          totalItems.value = response.data.zon;

          // 处理 sections 数据
          tableData.value = response.data.sections.map(item => ({
            ...item,
            section_status: item.section_status === 1, // 1 -> true, 0 -> false
          }));
        })
        .catch(error => {
          console.error('Error fetching data:', error);
        });
    }
    function qk() {
      form.section_name = '';
      form.section_charge = '';
      form.section_phone = '';
      form.section_email = '';
    }
    sx();

    const add = () => {
      dialogVisible.value = true;

      // 添加逻辑  
    };
    const addqr = () => {
      const requestData = {
        section_name: form.value.section_name || "默认部门名称",
        section_charge: form.value.section_charge,
        section_phone: form.value.section_phone,
        section_email: form.value.section_email,
        section_create_by: userId,
      };

      console.log('请求数据:', requestData); // 调试

      axios.post('http://localhost:5084/api/Section/AddSection', requestData)
        .then(function (response) {
          console.log(response.data);
          if (response.data) {
             ElMessage.error("增加成功");
            qk();
            sx();
            dialogVisible.value = false;
          }
        })
        .catch(function (error) {
          if (error.response) {
            console.error('验证错误:', error.response.data); // 记录验证错误
          } else {
            console.error('错误:', error.message);
          }
           ElMessage.error("增加失败，请检查输入数据");
        });
    };
    const upqr = () => {
      axios.put(`http://localhost:5084/api/Section/UPSection`, {
        section_id: form.value.section_id,
        section_name: form.value.section_name,
        section_charge: form.value.section_charge,
        section_phone: form.value.section_phone,
        section_email: form.value.section_email,
        section_update_by: userId,
      }).then(function (response) {
        console.log(response.data);
        if (response.data) {
           ElMessage.error("修改成功");
          qk();
          sx();
          dialogVisible1.value = false;
        } else {
           ElMessage.error("修改失败，请检查输入数据");
        }
      });
    };
    const edit = () => {
      // 编辑逻辑  
    };
    const handleSwitchChange = (row) => {
      console.log(row);
      const newStatus = row.section_status ? 1 : 0;
      axios.put('http://localhost:5084/api/Section/UPstatus?id=' + row.section_id + '&status=' + newStatus + '')
        .then(response => {
          console.log('状态更新成功:', response.data);
        })
        .catch(error => {
          console.error('状态更新失败:', error);
          // 如果更新失败，你可能需要重置开关的状态  
          /// 还原状态  
        });
    }

    const importData = () => {
      // 导入逻辑  
    };

    const query = () => {
      // 查询逻辑  
      console.log('Querying with:', searchTable.value);
      const status = selectedFilter.value === 'enabled' ? 1 : selectedFilter.value === 'disabled' ? 0 : '';
      // 确保 searchTable 是字符串
      const keyword = String(searchTable.value);
      console.log('查询参数:', {status,keyword,});
      axios.get(`http://localhost:5084/api/Section/MHCX?PageNumber=${currentPage.value}&PageSize=${pageSize.value}&status=${status}&sname=${keyword}`)
        .then(response => {
          console.log(response.data);

          // 更新总条目数
          totalItems.value = response.data.zon;

          // 处理 sections 数据
          tableData.value = response.data.sections.map(item => (
            { ...item,
              section_status: item.section_status === 1, // 1 -> true, 0 -> false
            }
          ))
        })
    };
    const reste=() => {
      selectedFilter.value = '';
      searchTable.value = '';
      sx();
    }
    const editRow = (row) => {
      // 编辑行逻辑
      dialogVisible1.value = true;
      form.value = row;
      console.log('Editing row:', row);
    };

    const deleteRow = (row) => {
      // 删除行逻辑  
      console.log('Deleting row:', row);
      if (confirm('确定要删除吗？')) {
        axios.delete(`http://localhost:5084/api/Section/DeSection?id=${row.section_id}`)
          .then(function (response) {
            console.log(response.data);
            if (response.data) {
               ElMessage.error("删除成功");
              sx();
            }
          })
          .catch(function (error) {
            console.error('错误:', error);
          })
      }
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
      // 分页逻辑  
      console.log('Current page:', page);
      sx();
    };

    // 确保所有函数都被返回  
    return {
      searchKey,
      treeData,
      defaultProps,
      tableData,
      selectedFilter,
      searchTable,
      currentPage,
      pageSize,
      totalItems,
      add,
      edit,
      importData,
      query,
      editRow,
      deleteRow,
      handleCurrentChange,
      dialogVisible,
      form,
      userId,
      addqr,
      dialogVisible1,
      form1,
      upqr,
      handleSwitchChange,
      reste
    };
  },
};  
</script>

<style>
.container {
  display: flex;
  gap: 20px;
  height: 87vh;
}

.sidebar {
  height: 100%;
  width: 30vh;
}

.main {
  width: 80%;
  flex: 1;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.eltable {
  height: 90%;
}

.letree {
  height: 97%;
}
</style>